<template>
  <el-dialog
    :visible.sync="dialogVisible"
    :before-close="handleClose"
    :append-to-body="false"
    :show-close="true"
    :close-on-click-modal="false"
    :class="{'mobile-el-dialog mobile-el-dialog-form': showMobilePage}"
    class="global-dailog-style create-resource"
  >
    <div :style="{maxHeight: '80vh'}" class="body-form">
      <el-form
        ref="editResouceForm"
        :model="editResouceForm"
        :rules="editResouceRules"
        :disabled="false"
        :label-position="formAlign"
        label-width="100px"
        class="lineHeight32">
        <div class="resource-top">
          <Title :title="'平台选择'" font-size="16px" >
            <div :style="showMobilePage?'width:200px; margin-left:24px;':''" class="tip">{{ !isEdit?'注意：创建成功后平台不可以进行修改，如要修改平台请新建资源':'当前资源所属平台无法变更，如要修改平台请新建资源' }}</div>
          </Title>
          <img v-if="isEdit" :src="accountStatusImg" class="contract-icon" alt="">
          <el-row :class="{'flex-wrap':showMobilePage, 'ordertype-box': !showMobilePage}" type="flex" class="flex-center mb20">
            <el-col :span="24">
              <el-form-item key="platformType" prop="platformType" label="平台" style="margin:17px 0 0 0 !important">
                <div class="label-item">
                  <selectWithoutHttp
                    v-if="!isEdit"
                    v-model="editResouceForm.platformType"
                    :list-data="platformList"
                    :disabled="platformTypeDisabled"
                    filterable
                    class="width240"
                    style="margin-right: 10px;"
                    placeholder="请选择平台"
                    @change="platformTypeChange"
                  />
                  <template v-else>
                    <platformIcon :data="editResouceForm.platformTypeName" />
                    <span style="margin-right: 32px;">{{ editResouceForm.platformTypeName }}</span>
                  </template>
                  <el-checkbox
                    v-model="editResouceForm.autoPick"
                    @change="autoPickChange">{{ platformDesc }}</el-checkbox>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <Title :title="'资源编辑'" font-size="16px" style="margin-bottom:16px">
          <div :style="showMobilePage?'width:200px;margin-left:24px;':''" class="tip">说明：以下内容为新建资源基础信息(*为必填项)，提交后可以填写更多信息</div>
        </Title>
        <div class="resource-edit">
          <el-row type="flex" class="flex-wrap">
            <el-col :span="rowSpan" class="responsive-col-lg-8 rel">
              <el-form-item
                :class="showMobilePage && 'mobile-el-item'"
                prop="resourceName"
                label="账号">
                <div class="flex-center">
                  <el-input
                    v-model.trim="editResouceForm.resourceName"
                    :disabled="resourceNameDisable"
                    :maxlength="50"
                    :type="'text'"
                    placeholder="请输入"
                    name="resourceName"
                    class="width240" />
                  <tipIcon content="提交后账号名称前后的空格会自动去除" class="warn-icon" style="margin-top:0;"/>
                </div>
              </el-form-item>
              <div
                v-if="hasResourceType === 1 && editResouceForm.resourceName"
                :class="{'flex-wrap':showMobilePage}"
                class="quick-tip">
                平台已登记类似账号，建议确认后再新建，<el-link type="primary" @click.native="quickFindResource">快速查看</el-link>
              </div>
            </el-col>
            <el-col :span="rowSpan" class="responsive-col-lg-8 rel">
              <div>
                <el-form-item
                  :class="showMobilePage && 'mobile-el-item'"
                  prop="resourceId"
                  label="账号ID">
                  <el-input
                    v-model.trim="editResouceForm.resourceId"
                    :disabled="resourceIdDisable"
                    :maxlength="500"
                    :type="'text'"
                    class="width240"
                    placeholder="请输入唯一标识ID"
                    name="resourceId"
                    clearable />
                </el-form-item>
              </div>
              <div v-if="hasResourceType === 2 && editResouceForm.resourceId" :class="{'flex-wrap':showMobilePage}" class="quick-tip">平台已登记该账号ID，无法重复创建，<el-link type="primary" @click.native="quickFindResource">快速查看</el-link></div>
            </el-col>
            <el-col :span="rowSpan" class="responsive-col-lg-8 rel">
              <el-form-item
                :class="showMobilePage && 'mobile-el-item'"
                :rules="resourceLinkRules"
                prop="resourceLink"
                label="主页链接">
                <div class="flex-center">
                  <el-input
                    v-model.trim="editResouceForm.resourceLink"
                    :disabled="resourceLinkDisable"
                    :maxlength="500"
                    :type="'text'"
                    name="resourceLink"
                    clearable
                    placeholder="请输入"
                    class="width240" />
                  <tipIcon :content="linkDisable && hasChoosePlatformType?'平台为微信视频号时链接无需填写':'请输入账号的主页链接<br>示例：https://space.bilibili.com/123456'" class="warn-icon" style="margin-top:0;" use-html/>
                </div>
              </el-form-item>
              <div v-if="hasResourceType === 3 && editResouceForm.resourceLink" class="quick-tip">平台已登记该链接，无法重复创建，<el-link type="primary" @click.native="quickFindResource">快速查看</el-link></div>
              <div v-else-if="!isLinkMatch && editResouceForm.resourceLink" class="quick-tip">你输入的链接可能与选择的平台不符</div>
            </el-col>
            <el-col :span="rowSpan" class="responsive-col-lg-8">
              <el-form-item
                prop="operateMode"
                label="运营模式">
                <el-cascader
                  v-model="editResouceForm.operateMode"
                  :props="{ emitPath: false }"
                  :options="operateModeList"
                  :disabled="operateModeDisable"
                  popper-class="tag-overflow"
                  clearable
                  filterable
                  name="operateMode"
                  class="width240"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row type="flex" class="flex-wrap">
            <el-col :span="rowSpan" :class="{'label-collapse-global': accountOperationRequired}" class="responsive-col-lg-8">
              <el-form-item
                :rules="accountOperationRules"
                :class="{'accountOperation': accountOperationDisable}"
                prop="accountOperation"
                label="其他运营人员">
                <div class="flex-center">
                  <select-with-user-load
                    :disabled="accountOperationDisable"
                    v-model="editResouceForm.accountOperation"
                    :default-list="defaultUserList || []"
                    :clearable="true"
                    :multiple="true"
                    :collapse-tags="false"
                    class="width240"
                    show-check-user
                    placeholder="请选择"
                    filterable
                  />
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="rowSpan" class="responsive-col-lg-8">
              <el-form-item
                :rules="attributionMatrixRules"
                label="所属经营体"
                prop="attributionMatrix">
                <el-cascader
                  v-model="editResouceForm.attributionMatrix"
                  :show-all-levels="false"
                  :options="deptTreeList"
                  :disabled="attributionMatrixDisable"
                  :props="{
                    emitPath:false,
                    value: 'id',
                    label: 'name',
                    checkStrictly: true,
                    multiple: false,
                  }"
                  popper-class="tag-overflow"
                  placeholder="请选择所属经营体"
                  size="small"
                  collapse-tags
                  filterable
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="rowSpan" class="responsive-col-lg-8">
              <el-form-item
                :rules="cooperationObjRules"
                prop="cooperation"
                label="合作运营方">
                <div class="flex-center">
                  <select-with-user-load
                    ref="mengliSuppliers"
                    v-model="editResouceForm.cooperationObj"
                    :disabled="cooperationObjDisable"
                    :loadmore-method="getSupplier({ onlyChannel: true })"
                    :hide-select-list="editResouceForm.cooperationObj ? [editResouceForm.cooperationObj] : []"
                    :clearable="true"
                    :key-name="'supplierName'"
                    :add-new="true"
                    placeholder="请选择"
                    value-type="object"
                    label-name="supplierName"
                    extend-class="image"
                    filterable
                    class="width240"
                    collapse-tags
                    @change="suppliersChange"
                    @clear="clearSupplier"
                    @addNewClick="goCreateSupplier"
                  />
                  <tipIcon content="飞博供应商" class="warn-icon" style="margin-top:0;"/>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="rowSpan" class="responsive-col-lg-8">
              <el-form-item label="供应商类型" prop="supplierType">
                <el-select
                  v-if="editResouceForm.cooperation"
                  v-model="editResouceForm.supplierType"
                  disabled
                  clearable
                  placeholder="--"
                  size="small"
                  class="width240"
                >
                  <el-option
                    v-for="(select, index) in supplierType"
                    :key="index"
                    :label="select.value"
                    :value="select.id" />
                </el-select>
                <div v-else :style="showMobilePage?'width:208px':''" class="mock-input">--</div>
              </el-form-item>
            </el-col>
            <el-col :span="rowSpan" class="responsive-col-lg-8">
              <el-form-item label="是否挂靠" prop="microTask">
                <div class="flex-center">
                  <el-select
                    v-model="editResouceForm.microTask"
                    :disabled="microTaskDisable"
                    value-key="id"
                    clearable
                    size="small"
                    class="width240"
                  >
                    <el-option
                      v-for="(select, index) in microTaskData"
                      :key="index"
                      :label="select.value"
                      :value="select.id" />
                  </el-select>
                  <tipIcon v-if="microTaskTip" :content="microTaskTip" class="warn-icon" style="margin-top:0;"/>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="rowSpan" class="responsive-col-lg-8">
              <!-- 协作部门暂时隐藏 -->
              <el-form-item label="协作部门" prop="cooperationDepartment">
                <filter-cascader
                  v-model="cooperationDepartment"
                  :options="deptTreeList"
                  :disabled="!hasChoosePlatformType"
                  popper-class="tag-overflow"
                  placeholder="请选择协作部门"
                />
              </el-form-item>
            </el-col>
            <el-col :span="rowSpan" class="responsive-col-lg-8">
              <el-form-item label="标签" prop="tag">
                <div class="flex-center">
                  <TagSelect ref="tagRef" v-model="editResouceForm.tag" :collapse-tags="false" :module-type="TAG_MODULES.RESOURCE" :platform="editResouceForm.platformType" :need-plat-form-params="true" limit class="width240"/>
                  <tipIcon content="标签最多可选择3个" class="ml5"/>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="rowSpan" class="responsive-col-lg-8">
              <el-form-item label="内容标签" prop="additionalKey.tagRemark">
                <el-input v-model="editResouceForm.additionalKey.tagRemark" placeholder="请输入" class="width240" type="text" maxlength="200"/>
              </el-form-item>
            </el-col>
            <el-col :span="rowSpan" class="responsive-col-lg-8">
              <el-form-item label="跟进人" prop="followUsers">
                <div class="flex-center">
                  <selectWithUserLoad
                    ref="proposerRef"
                    v-model="editResouceForm.followUsers"
                    :hide-select-list="editResouceForm.followUsers || []"
                    :show-check-user="true"
                    :value-type="'object'"
                    class="width240"
                    key-name="id"
                    label-name="userName"
                    multiple
                    filterable/>
                  <tipIcon content="跟进人拥有该账号自动生成结算单的权限" class="warn-icon" style="margin-top:0;"/>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="rowSpan" class="responsive-col-lg-8">
              <el-form-item label="是否新号" prop="isNewAccount">
                <selectWithoutHttp
                  v-model="editResouceForm.additionalKey.isNewAccount"
                  :list-data="newAccountOptions"
                  clearable
                  class="width240"
                  style="margin-right: 10px;"
                  placeholder="请选择"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>
    </div>
    <fixed-pagination style="width: 100%; padding: 0; margin: 0; border-radius: 0px 0px 8px 8px">
      <div class="center mobile-btn-group">
        <el-button :loading="loading" class="mobile-btn-flex" type="primary" size="small" @click="toSave('editResouceForm')">保存</el-button>
        <el-button type="info" class="back-btn cancel-btn-style" size="small" plain @click="handleClose">取消</el-button>
      </div>
    </fixed-pagination>
  </el-dialog>
</template>
<script>
import createMixins from '../create/model/createMixins';
import mobileCreate from '@/mixins/mobileCreate';
import { addResource, editAccountInfo } from '@/api/resource';

export default {
  components: {
  },
  mixins: [createMixins, mobileCreate],
  data() {
    return {
      dialogVisible: false,
      editResouceForm: {
        resourceType: 0, // v2.0.2 不允许切换类型，默认内品，所以修改成 resourceType = 0 。time: 2020-5-29
        resourceName: '',
        resourceId: '',
        resourceLink: '', // 链接 v2.0.2 新增 time:2019.05.29
        operateMode: [], // 运营模式 v2.0.2 新增 time:2019.05.29
        cooperation: '', // 合作运营方 v2.0.2 新增 time:2019.05.29
        attributionMatrix: '', // 所属经营体
        accountOperation: [], // 运营人员
        microTask: '',
        platformType: '',
        tag: [],
        supplierType: '',
        cooperationObj: null,
        autoPick: false, // 是否开启自动采集
        followUsers: [],
        additionalKey: {
          isNewAccount: 0,
          tagRemark: ''
        }
      }
    };
  },
  computed: {
    rowSpan() {
      return this.showMobilePage ? 24 : 12;
    }
  },
  // 自营，合作运营，独家代理，其他
  created() {
    // 用于监听新建合作运营方的事件
    window.addEventListener('storage', (e) => {
      this.getSupplier();
      localStorage.removeItem('freshResource');
    });
  },
  methods: {
    async openDialog(params) {
      // 获取所属平台
      this.getPlatformList();
      // 获取供应商
      this.getSupplier();
      // 部门
      await this.queryDeptTreeList();
      // 运营模式
      await this.getOperateoptions();
      const { data } = params || {};
      if (data) {
        this.resourceId = Number(data.id) || '';
        this.setData(data);
      }
      if (params.supplier) {
        const { supplier, supplierId, supplierType } = params;
        this.editResouceForm.cooperation = params.supplier;
        this.$set(this.editResouceForm, 'supplierType', supplierType === 0 ? 1 : 0);
        this.editResouceForm.cooperationObj = {
          supplierId,
          supplierName: supplier,
          supplierType
        };
      }
      this.$nextTick(() => {
        this.$refs.editResouceForm && this.$refs.editResouceForm.clearValidate();
        this.dialogVisible = true;
      });
    },
    setData(data, fromSignAndFinished = false) {
      this.fromSignAndFinished = fromSignAndFinished;
      if (data.operateMode && Array.isArray(data.operateMode)) {
        data.operateMode = data.operateMode[data.operateMode.length - 1];
      }
      const accountOperation = JSON.parse(JSON.stringify(data.accountOperation));
      if (accountOperation && accountOperation.length) {
        data.accountOperation = accountOperation.map(i => {
          this.defaultUserList.every(user => user.id !== i.id) && this.defaultUserList.push({
            id: i.id,
            userName: i.value
          });
          return i.id;
        });
      }
      data.resourceType = 0;
      if (data.cooperationDepartment) {
        this.cooperationDepartment = data.cooperationDepartment.map(i => i.id);
      }
      if (!data.resourceLink) data.resourceLink = '';
      if (!data.operateMode) data.operateMode = '';
      if (!data.cooperation) data.cooperation = '';
      this.historyAccountOperation = data.historyAccountOperation || [];
      if (!this.isNodeIdExistInTree(data.attributionMatrix, this.deptTreeList)) {
        data.attributionMatrix = '';
      }
      if (!data.additionalKey)data.additionalKey = {};
      this.editResouceForm = data;
      if (data.followUsers && data.followUsers.length > 0) {
        data.followUsers = data.followUsers.map(item => {
          item.userName = item.name;
          return item;
        });
      }
      this.$set(this.editResouceForm, 'followUsers', data.followUsers || []);
      if (data.channelId) {
        this.editResouceForm.cooperationObj = {};
        this.editResouceForm.cooperationObj.supplierName = data.cooperation;
        this.editResouceForm.cooperationObj.supplierType = data.supplierType;
        this.editResouceForm.cooperationObj.supplierId = data.channelId;
      }
      // 编辑时切换合作模式回填默认值
      this.editDefaultData = {
        'accountOperation': data.accountOperation,
        'attributionMatrix': data.attributionMatrix,
        'cooperationObj': this.editResouceForm.cooperationObj,
        'supplierType': data.supplierType
      };
    },
    add(params) {
      addResource(params).then((res) => {
        this.loading = false;
        if (res.code === 200) {
          this.$message.success('添加成功');
          this.handleClose();
          this.$emit('success');
        } else {
          this.$message.error(res.message);
        }
      }, result => {
        this.loading = false;
      });
    },
    edit(params) {
      editAccountInfo(params).then(({ data, code, message }) => {
        this.loading = false;
        if (this.platformTypeName) this.editResouceForm.platformTypeName = this.platformTypeName;
        if (this.attributionMatrixName) this.editResouceForm.attributionMatrixName = this.attributionMatrixName;
        localStorage.setItem('isSuccess', true);
        localStorage.setItem('changeData', JSON.stringify(this.editResouceForm));
        this.$message.success('修改成功');
        this.$emit('success');
        this.handleClose();
      }, result => {
        this.loading = false;
      });
    },
    async toSave(formValue) {
      const params = JSON.parse(JSON.stringify(this.editResouceForm));
      this.isSave = true;
      this.$refs[formValue].validate((valid) => {
        this.isSave = false;
        if (valid) {
          if (params.tag && params.tag.length > 3) {
            this.$message.warning('标签最多可选择3个');
            return;
          }
          params.channelId = params.cooperationObj ? params.cooperationObj.supplierId : null;// 3.0.3编辑时对channelId赋值
          params.cooperationDepartment = this.cooperationDepartment;
          params.resourceId = params.resourceId.trim();
          params.resourceName = params.resourceName.trim();
          params.resourceLink = params.resourceLink.trim();
          params.historyAccountOperation = this.historyAccountOperation.map(i => i.id);
          if (params.operateMode && !Array.isArray(params.operateMode)) {
            params.operateMode = [params.operateMode];
          }
          if (Array.isArray(params.followUsers)) {
            params.followUsers = params.followUsers.map(item => {
              return item.id;
            }).join();
          }
          this.loading = true;
          if (!this.isEdit) {
            this.add(params);
          } else {
            const editParams = this.getEditParams(params);
            this.edit(editParams);
          }
        } else {
          this.$message.warning('请检查信息是否填写完整');
          return false;
        }
      });
    },
    getEditParams(params) {
      let data = {
        id: '',
        resourceType: 0, // v2.0.2 不允许切换类型，默认内品，所以修改成 resourceType = 0 。time: 2020-5-29
        resourceName: '',
        resourceId: '',
        resourceLink: '', // 链接 v2.0.2 新增 time:2019.05.29
        operateMode: [], // 运营模式 v2.0.2 新增 time:2019.05.29
        accountOperation: [], // 运营人员
        channelId: '', // 合作运营方
        attributionMatrix: '', // 所属经营体
        cooperationDepartment: [],
        microTask: '',
        tag: [],
        supplierType: '',
        followUsers: [],
        isNewAccount: 0,
        tagRemark: ''
      };
      Object.keys(data).forEach(key => {
        if (params[key] || params[key] === 0) { data[key] = params[key]; }
      });
      if (Array.isArray(data.followUsers)) {
        data.followUsers = data.followUsers.map(item => {
          return item.id;
        }).join();
      }
      const { isNewAccount, tagRemark } = params.additionalKey || {};
      data = Object.assign(data, { isNewAccount, tagRemark });
      data.id = params.systemId;
      if (!this.fromSignAndFinished) delete data.signUpId;
      return data;
    },
    handleClose() {
      this.editResouceForm = {
        resourceType: 0, // v2.0.2 不允许切换类型，默认内品，所以修改成 resourceType = 0 。time: 2020-5-29
        resourceName: '',
        resourceId: '',
        resourceLink: '', // 链接 v2.0.2 新增 time:2019.05.29
        operateMode: [], // 运营模式 v2.0.2 新增 time:2019.05.29
        cooperation: '', // 合作运营方 v2.0.2 新增 time:2019.05.29
        attributionMatrix: '', // 所属经营体
        accountOperation: [], // 运营人员
        microTask: '',
        platformType: '',
        tag: [],
        supplierType: '',
        cooperationObj: null,
        autoPick: false, // 是否开启自动采集
        followUsers: [],
        additionalKey: {
          isNewAccount: 0,
          tagRemark: ''
        }
      };
      this.$refs.tagRef.clearTags();
      this.editDefaultData = {};
      this.fromSignAndFinished = false;
      this.dialogVisible = false;
    }
  }
};
</script>
<style  lang="scss" scoped>
.create-resource {
  .body-form {
    padding-bottom: 50px;
    @include scrollBar($x: hidden, $y: auto, $width: 6px);
  }
  padding-top: 16px;
  box-shadow: 2px 4px 10px #DDE1EA;
  & ::v-deep {
    .el-dialog {
      width: 960px;
    }
    .el-dialog__body {
      padding: 6px 24px 24px 24px;
    }
    .el-form-item {
      .el-select {
        width: 240px;
      }
      .el-cascader{
        width: 240px;
      }
      .el-input__inner  {
        width: 240px;
        height: 32px;
      }
      .el-textarea__inner {
        height: 64px !important;
      }
      .el-form-item__label {
        color: #666;
        height: 32px;
      }
    }
  }
  .warn-icon {
    width: 14px;
    height: 14px;
    margin: 8px 0 0 4px;
  }
  .resource-top {
    position: relative;
    .contract-icon {
      position: absolute;
      right: 20px;
      top: 20px;
      z-index: 10;
      width: 110px;
    }
    .center{
      display: flex;
      align-items: center;
    }
  }
  .quick-tip {
    position: absolute;
    left: 100px;
    top: 35px;
    font-size:12px;
    font-family:PingFangSC-Regular,PingFang SC;
    font-weight:400;
    color:rgba(153,153,153,1);
    line-height:14px;
    white-space: nowrap;
    display: flex;
    align-items: center;
  }
  .width240 {
    width: 240px;
    & ::v-deep {
      .el-input__inner, .el-select {
        width: 240px;
      }
    }
  }
}
.mobile-create {
  .contract-icon {
    width: 70px !important;
  }
}
.flex-wrap {
  flex-wrap: wrap;
  position: relative;
  &.quick-tip {
    left: 94px;
  }
}
.tip {
  font-size:12px;
  font-family:PingFangSC-Regular,PingFang SC;
  font-weight:400;
  color:rgba(153,153,153,1);
  line-height:14px;
  margin-left: 8px;
  margin-top: 4px;
}
.ordertype {
  font-size:14px;
  font-family:PingFangSC-Regular,PingFang SC;
  line-height:14px;
  margin:0 19px 0px 10px;
  color:rgba(153,153,153,1);
}
.label-item {
  display: flex;
  align-items: center;
  font-size: 14px;
}
.mock-input {
  width: 240px;
  height: 32px;
  padding: 0 8px;
  border: 1px solid #E4E7ED;
  border-radius: 4px;
  color: #C0C4CC;
  background-color: #F5F7FA;
  line-height: 32px;
  font-size: 14px;
  cursor: not-allowed;
}
</style>
<style lang="scss">
.create-resource{
  .el-icon-info:before {
    font-size: 14px;
    color:rgba(153,153,153,1);
  }
  .el-input__suffix {
    line-height: 28px;
  }
  .el-select-dropdown__item {
    max-width: 235px !important;
  }
  .accountOperation{
    .el-select__input{
      cursor: not-allowed;
    }
  }
  .response-create-row {
    display: flex;
    flex-wrap: wrap;
    @media only screen and (min-width: 1490px) {
      .responsive-col-lg-8 {
        width: 33.33333%;
      }
    }
  }
}
</style>

